package sync.hw.demo02;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lwj
 * @date 2025-03-12
 * @vesion 1.0.0
 */
public class MyRunnable implements Runnable{
    /**
     * 用户信息
     */
    private UserInfo userInfo;
    /**
     * lock
     */
    private ReentrantLock reentrantLock = new ReentrantLock();

    // 构造方法
    public MyRunnable() {}
    public MyRunnable(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    @Override
    public void run() {
        try{
            // 加锁
            reentrantLock.lock();

            System.out.println(userInfo.getName()+":");

            char[] chars = userInfo.getContent();
            for (int i = 0; i < chars.length; i++) {
                System.out.print(chars[i]);
            }
            System.out.println(" ");
        } finally {
            // 解锁
            reentrantLock.unlock();
        }
    }

    // 同步方法方式
    private synchronized void cell() {
        System.out.println(userInfo.getName()+":");
        char[] chars = userInfo.getContent();
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]);
        }
        System.out.println(" ");
    }
}
